package Chan

import (
	"sync"
)

type TempEvent struct {
	eventMap sync.Map
}

type te struct {
	key     string
	event   *Event
	timeout int64
}

func NewTempEvent() *TempEvent {
	ptr := &TempEvent{}
	return ptr
}

func (e *TempEvent) Notify(key string, data interface{}) {
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	val, ok := e.eventMap.Load(key)
	if ok != true {
		return
	}
	te := val.(*te)

	te.event.Notify(data)
}

func (e *TempEvent) Wait(key string, timeout int64) (message interface{}) {
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	// 创建一个te，并保存起来
	te := &te{}
	te.key = key
	te.timeout = timeout
	te.event = NewEvent()

	// 记录数据
	e.eventMap.Store(key, te)

	// 等待等待事件
	message = te.event.Wait(te.timeout)

	// 删除数据
	e.eventMap.Delete(key)

	// 释放事件
	te.event.Close()

	return message
}
